package cc.wfu.trigger.http;

import cc.common.types.entity.CartEntity;
import cc.wfu.domain.cart.service.CartService;
import cc.wfu.trigger.api.ICartServiceApi;
import cc.wfu.type.annotation.PreAntAuthorize;
import cc.wfu.type.annotation.PreAntAuthorizeValue;
import cc.wfu.type.service.JwtAuthService;
import cc.wfu.type.trigger.api.dto.VerifyJwtTokenRequest;
import cc.wfu.types.exception.AppException;
import cc.wfu.types.model.Response;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

/**
 * @Author: jia-qiang ljq1024.cc
 * @desc:
 * @Date: 2024-05-22-17:33
 */
@Slf4j
@AllArgsConstructor
@RequestMapping("/cart/")
@RestController("cart_controller")
//@CrossOrigin("${app.config.cross-origin}")
public class CartController implements ICartServiceApi {

    @Resource
    protected CartService cartService;
    @Resource
    protected JwtAuthService jwtService;

    @PreAntAuthorize(value = PreAntAuthorizeValue.hasAnyRole, antAuthorities = {"USER"})
    @RequestMapping(value = "/test", method = RequestMethod.GET)
    public String test() {
        return "test";
    }

    /**
     * 增加购物车
     */
    @RequestMapping(value = "/test222", method = RequestMethod.POST)
    public Response<String> test22() {
        try {
            log.info("增加购物车 - 开始 ");
            return null;
        } catch (AppException e) {
            log.error("增加购物车 - 出现业务异常 - error:", e);
            return Response.APP_ERROR(e.getMessage());
        } catch (Exception e) {
            log.error("增加购物车 - 出现未知异常 - error:", e);
            return Response.UN_ERROR();
        }
    }

    /**
     * 增加购物车
     * @param cartEntity 购物车实体
     */
    @Override
    @PreAntAuthorize(value = PreAntAuthorizeValue.hasAnyRole, antAuthorities = {"USER"})
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Response<String> addShopCart(@RequestHeader("Authorization") String token, @RequestBody CartEntity cartEntity) {
        try {
            log.info("增加购物车 - 开始");
            // 0. 获取基础数据
            BigDecimal amount = cartEntity.getAmount(); // 支付金额
            Long sku = cartEntity.getSku(); // 商品sku
            String productTitle = cartEntity.getProductTitle(); // 商品名
            String productMerchant = cartEntity.getProductMerchant(); // 商户名
            Integer totalCount = cartEntity.getTotalCount(); // 商品总数量

            // 1. 参数校验
            if (amount == null || sku == null || totalCount == null
                    || !StringUtils.hasLength(productTitle) || !StringUtils.hasLength(productMerchant)) {
                log.warn("增加购物车 - 参数错误 - params: {}", cartEntity);
                return Response.ILLEGAL_PARAMETER();
            }

            String userId = jwtService.getUserId(VerifyJwtTokenRequest.builder().jwtToken(token).build(), "userId");

            // 2. 操作数据库
            cc.wfu.domain.cart.model.entity.CartEntity entity = cc.wfu.domain.cart.model.entity.CartEntity.builder()
                        .userId(userId)
                        .sku(cartEntity.getSku())
                        .productCover(cartEntity.getProductCover())
                        .productMerchant(cartEntity.getProductMerchant())
                        .productTitle(cartEntity.getProductTitle())
                        .totalCount(cartEntity.getTotalCount())
                        .amount(cartEntity.getAmount())
                        .build();
            cartService.addShopCart(entity);
            log.info("增加购物车 - 结束");
            return Response.SUCCESS();
        } catch (AppException e) {
            log.error("增加购物车 - 出现业务异常 - error:", e);
            return Response.APP_ERROR(e.getMessage());
        } catch (Exception e) {
            log.error("增加购物车 - 出现未知异常 - error:", e);
            return Response.UN_ERROR();
        }
    }


    /**
     * 查询购物车
     */
    @Override
    @PreAntAuthorize(value = PreAntAuthorizeValue.hasAnyRole, antAuthorities = {"USER"})
    @RequestMapping(value = "/query", method = RequestMethod.POST)
    public Response<List<cc.wfu.domain.cart.model.entity.CartEntity>> queryShopCart(@RequestHeader("Authorization") String token) {
        try {
            log.info("查询购物车 - 开始");
            // 1. 获取用户信息
            String userId = jwtService.getUserId(VerifyJwtTokenRequest.builder().jwtToken(token).build(), "userId");

            // 2. 操作数据库
            List<cc.wfu.domain.cart.model.entity.CartEntity> response = cartService.queryShopCart(userId);
    
            log.info("查询购物车 - 结束");
            return Response.SUCCESS(response);
        } catch (AppException e) {
            log.error("查询购物车 - 出现业务异常 - error:", e);
            return Response.APP_ERROR(e.getMessage());
        } catch (Exception e) {
            log.error("查询购物车 - 出现未知异常 - error:", e);
            return Response.UN_ERROR();
        }
    }

    /**
     * 删除购物车
     * @param token 权限信息
     * @param cartId 购物车id
     */
    @Override
    @PreAntAuthorize(value = PreAntAuthorizeValue.hasAnyRole, antAuthorities = {"USER"})
    @RequestMapping(value = "/delete/{cartId}", method = RequestMethod.POST)
    public Response<String> deleteShopCart(@RequestHeader("Authorization") String token, @PathVariable("cartId") String cartId) {
        try {
            log.info("删除购物车 - 开始");
            String userId = jwtService.getUserId(VerifyJwtTokenRequest.builder().jwtToken(token).build(), "userId");
            cartService.deleteCart(userId, cartId);
            return Response.SUCCESS();
        } catch (AppException e) {
            log.error("删除购物车 - 出现业务异常 - error:", e);
            return Response.APP_ERROR(e.getMessage());
        } catch (Exception e) {
            log.error("删除购物车 - 出现未知异常 - error:", e);
            return Response.UN_ERROR();
        }
    }
}
